//
//  PayMoneyNewDetailViewController.m
//  PropertyManager
//
//  Created by TNG on 2018/7/31.
//  Copyright © 2018年 Tng. All rights reserved.
//

#import "PayMoneyNewDetailViewController.h"

@interface PayMoneyNewDetailViewController () <UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) UITableView * tableview;
@property (strong, nonatomic) UIButton * btn;

@end

@implementation PayMoneyNewDetailViewController

static NSString * cellID = @"cell";
static NSString * PayMoneyNewDetailInfoTableViewCellID = @"PayMoneyNewDetailInfoTableViewCell";
static NSString * PayMoneyNewContractNunTableViewCellID = @"PayMoneyNewContractNunTableViewCell";
static NSString * PayMoneyNewDegreeNumTableViewCellID = @"PayMoneyNewDegreeNumTableViewCell";
static NSString * PayMoneyNewHealthTableViewCellID = @"PayMoneyNewHealthTableViewCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatTableview];
    [self registCell];
    if (self.isPay) {
        [self.view addSubview:self.btn];
    }
    [self wr_setNavBarShadowImageHidden:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AliPayDidBack:) name:@"AliPayDidBack" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weiXinPayDidBack:) name:@"weiXinPayDidBack" object:nil];
}

#pragma mark -微信回调
-(void)weiXinPayDidBack:(NSNotification *)notice
{
    WeakSelf;
    NSDictionary * dic = notice.userInfo;
    NSString * code = dic[@"code"];
    if ([code isEqualToString:@"0"]) {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"支付成功" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            ElectronTicketViewController * ctr =[[ElectronTicketViewController alloc] init];
            [weakSelf.navigationController pushViewController:ctr animated:YES];
        }];
        [alert addAction: action1];
        [self presentViewController:alert animated:YES completion:nil];
    }else
    {
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"支付失败" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction: action1];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

#pragma mark - 支付宝回调
-(void)AliPayDidBack:(NSNotification *)notice
{
    NSDictionary * dic = notice.userInfo;
    NSString * str =dic[@"resultStatus"];
    NSString * payMessage  = @"支付失败";
    if ([str isEqualToString:@"6001"]) {
        payMessage  = @"支付失败";
    }else if([str isEqualToString:@"6002"])
    {
        payMessage  = @"网络延迟,请稍后再试";
    }else if([str isEqualToString:@"9000"])
    {
        payMessage  = @"支付成功";
    }else
    {
        payMessage  = @"交易延迟,请稍后再试";
    }
    WeakSelf;
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:payMessage message:@"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        PaySucceedViewController * ctr =[[PaySucceedViewController alloc] init];
//        [weakSelf.navigationController pushViewController:ctr animated:YES];
    }];
    [alert addAction: action1];
    [weakSelf presentViewController:alert animated:YES completion:nil];
}

-(void)registCell
{
    [self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:cellID];
    [self.tableview registerClass:[PayMoneyNewDetailInfoTableViewCell class] forCellReuseIdentifier:PayMoneyNewDetailInfoTableViewCellID];
    [self.tableview registerClass:[PayMoneyNewContractNunTableViewCell class] forCellReuseIdentifier:PayMoneyNewContractNunTableViewCellID];
    [self.tableview registerClass:[PayMoneyNewDegreeNumTableViewCell class] forCellReuseIdentifier:PayMoneyNewDegreeNumTableViewCellID];
    [self.tableview registerClass:[PayMoneyNewHealthTableViewCell class] forCellReuseIdentifier:PayMoneyNewHealthTableViewCellID];
}

-(void)creatTableview{
    if (self.tableview == nil) {
        UITableView * tableview;
        if (self.isPay) {
            tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kStatusAndNavBarH, WIDTH, HEIGHT - kStatusAndNavBarH - kHomeLineH - 50) style:UITableViewStyleGrouped];
        }else
        {
            tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, kStatusAndNavBarH, WIDTH, HEIGHT - kStatusAndNavBarH - kHomeLineH) style:UITableViewStyleGrouped];
        }
        tableview.delegate = self;
        tableview.dataSource = self;
        if (@available(iOS 11.0, *)) {
            tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
        }
        self.tableview = tableview;
        [self.view addSubview:self.tableview];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 96;
    }else if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            return 45;
        }
//        else
//        {
//            return 71;
//        }
        return 71;
    }else //if (indexPath.section == 2)
    {
        return 71;
    }
//    else
//    {
//        return 72;
//    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 10)];
    line.backgroundColor = SFMColor(239, 239, 244);
    return line;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
//        return 2;
        return 3;
    }
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PayMoneyNewDetailInfoTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PayMoneyNewDetailInfoTableViewCellID];
        [cell send];
        return cell;
    }else if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            PayMoneyNewContractNunTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PayMoneyNewContractNunTableViewCellID];
            [cell send];
            return cell;
        }else
        {
            PayMoneyNewDegreeNumTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PayMoneyNewDegreeNumTableViewCellID];
            if(indexPath.row == 1)
            {
                cell.moneyLabel.text = @"租金：¥10";
            }else
            {
                cell.moneyLabel.text = @"管理费：¥45";
            }
            return cell;
        }
    }else //if (indexPath.section == 2)
    {
        PayMoneyNewDegreeNumTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PayMoneyNewDegreeNumTableViewCellID];
        cell.moneyLabel.text = @"管理费：¥45";
        return cell;
    }
//    else
//    {
//        PayMoneyNewHealthTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:PayMoneyNewHealthTableViewCellID];
//        [cell send];
//        return cell;
//    }
//    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
//    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(UIButton *)btn
{
    if (_btn == nil) {
        _btn = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableview.frame), WIDTH, 50)];
        [_btn setTitle:@"确认缴费" forState:UIControlStateNormal];
        _btn.titleLabel.font = font(16);
        [_btn setBackgroundColor:SFMNavBarColor];
        [_btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btn;
}

#pragma mark - 确认缴费
-(void)btnClick:(UIButton *)btn{
    WeakSelf;
    [[PayMedthView shareView] showView];
    [PayMedthView shareView].payMedthChooseTypeEventBlock = ^(int payType) {
        if (payType == payMedthodWayOfAliPay) {
            [weakSelf AliPay];
        }else if(payType == payMedthodWayofWeiChat) {
            [weakSelf weiXinPay];
        }
    };
}

#pragma mark - 支付宝支付
-(void)AliPay{
//    NSMutableDictionary * params = [NSMutableDictionary dictionary];
//    [params setValue:SFMToken forKey:@"access_token"];
//    [params setValue:self.money forKey:@"totalAmount"];
//    WeakSelf;
//    [[TNGHTTP shareHttpClient] requestWithPath:@"app/user/alipay" AndParams:params AndReturnBlock:^(NSDictionary *dic) {
//        NSString *appScheme = @"FiveEightLaHuoAPP";
//        NSString * orderString = dic[@"orderString"];
//        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
//            NSString * str =resultDic[@"resultStatus"];
//            NSString * payMessage  = @"支付失败";
//            if ([str isEqualToString:@"6001"]) {
//                payMessage  = @"支付失败";
//            }else if([str isEqualToString:@"6002"])
//            {
//                payMessage  = @"网络延迟,请稍后再试";
//            }else if([str isEqualToString:@"9000"])
//            {
//                payMessage  = @"支付成功";
//                [weakSelf moneyDidChange];
//            }else
//            {
//                payMessage  = @"交易延迟,请稍后再试";
//            }
//            UIAlertController * alert = [UIAlertController alertControllerWithTitle:payMessage message:@"" preferredStyle:UIAlertControllerStyleAlert];
//            UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//    ElectronTicketViewController * ctr =[[ElectronTicketViewController alloc] init];
//    [weakSelf.navigationController pushViewController:ctr animated:YES];
//            }];
//            [alert addAction: action1];
//            [weakSelf presentViewController:alert animated:YES completion:nil];
//            weakSelf.sureBtn.userInteractionEnabled = YES;
//        }];
//    }AndFailMessage:^(NSString * message) {
//        [MBProgressHUD showMessageWithDelay:message delay:2];
//        weakSelf.sureBtn.userInteractionEnabled = YES;
//    }];
}

#pragma mark - 微信支付
-(void)weiXinPay
{
//    int money = [self.money floatValue]*100;
//
//    NSMutableDictionary * params = [NSMutableDictionary dictionary];
//    [params setValue:SFMsignKey forKey:@"signKey"];
//    [params setValue:[NSString stringWithFormat:@"%d",money] forKey:@"txnAmt"];
//
//    WeakSelf;
//    [[TNGHTTP shareHttpClient] requestWithPath:@"app/unionpay/wxApppay" AndParams:params AndReturnBlock:^(NSDictionary *dic) {
//        NSDictionary * dict = dic[@"map"];
//        NSString * partnerId = [NSString stringWithFormat:@"%@",dict[@"mch_id"]];
//        NSString * prepayId  = [NSString stringWithFormat:@"%@",dict[@"prepay_id"]];
//        NSString * nonceStr  = [NSString stringWithFormat:@"%@",dict[@"nonce_str"]];
//        NSString * sign      = [NSString stringWithFormat:@"%@",dict[@"sign"]];
//        NSString * timestamp = [NSString stringWithFormat:@"%@",dict[@"timestamp"]];
//
//        //调起微信支付
//        PayReq * req            = [[PayReq alloc] init];
//        req.partnerId           = partnerId;
//        req.prepayId            = prepayId;
//        req.nonceStr            = nonceStr;
//        req.timeStamp           = [timestamp intValue];
//        req.sign                = sign;
//        req.package             = @"Sign=WXPay";
//        [WXApi sendReq:req];
//        weakSelf.sureBtn.userInteractionEnabled = YES;
//    }AndFailMessage:^(NSString * message) {
//        [MBProgressHUD showMessageWithDelay:message delay:2];
//        weakSelf.sureBtn.userInteractionEnabled = YES;
//    }];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AliPayDidBack" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"weiXinPayDidBack" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
